package com.example.app.dialog

import android.content.Context
import android.graphics.Color
import android.graphics.drawable.ColorDrawable
import android.webkit.WebView
import androidx.collection.ArrayMap
import androidx.core.view.isVisible
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ScreenUtils
import com.blankj.utilcode.util.Utils
import com.example.app.R
import com.example.app.base.BaseBottomDialog
import com.example.app.databinding.DialogBottomWebBinding
import com.example.app.webview.AgentWebBuilder
import com.example.app.webview.WebURL
import com.lxj.xpopup.XPopup
import com.weikaiyun.fragmentation.SupportFragment

/**
 * Description: 底部的列表对话框
 * Create by dance, at 2018/12/16
 */
class CommonWebDialog(context: Context) : BaseBottomDialog<DialogBottomWebBinding>(context) {

    override fun getImplLayoutId() = R.layout.dialog_bottom_web
    override fun getViewBinding() = DialogBottomWebBinding.bind(popupImplView)
    override fun getMaxHeight() = dialogHeight

    private val errorLayoutId = R.layout.app_state_view_retry
    private val errorReLoadBtnId = R.id.layoutRetry
    private val webBGColor = R.color.color_white

    companion object {
        fun show(
            fragment: SupportFragment,
            webUrl: String,
            params: ArrayMap<String, Any?>? = null,
            dialogHeight: Int = ScreenUtils.getScreenHeight() * 2 / 3,  //弹窗高度，0为全屏默认设计高度
        ): CommonWebDialog? {
            val commonParamMap = WebURL.getCommonParam()
            var paramsStr = if (webUrl.contains("?")) "&" else "?"
            if (!params.isNullOrEmpty()) {
                commonParamMap.putAll(params)
            }
            commonParamMap.forEach { (k, v) -> paramsStr = "$paramsStr$k=$v&" }

            fragment.context?.let {
                val dialog = CommonWebDialog(it).apply {
                    this.fragment = fragment
                    this.dialogHeight = dialogHeight
                    this.webUrl = "${webUrl}${paramsStr.dropLast(1)}"
                }

                XPopup.Builder(it)
                    .isDestroyOnDismiss(true)
                    .enableDrag(false)
                    .asCustom(dialog)
                    .show()

                return dialog
            } ?: run {
                return null
            }
        }
    }

    private var fragment: SupportFragment? = null
    private var dialogHeight = 0
    private var webUrl = ""
    private var mAgentWebBuilder: AgentWebBuilder? = null
    private val webCallBack = object : AgentWebBuilder.AgentBuildCallBack {
        override fun onAgentWebPageFinished(view: WebView?, url: String?) {
            LogUtils.iTag(TAG, "onPageFinished  url = $url")
            mViewBinding?.pbLoading?.isVisible = false
        }

        override fun onAgentWebReceivedTitle(view: WebView?, title: String?) {
            //LogUtils.iTag(TAG, "onWebReceivedTitle title=$title")
        }
    }

    override fun onCreate() {
        super.onCreate()
        mViewBinding = DialogBottomWebBinding.bind(popupImplView)
        mViewBinding?.pbLoading?.isVisible = true
        initWebView()
    }

    override fun onDialogResume() {
        super.onDialogResume()
        mAgentWebBuilder?.onResume()
    }

    override fun onDialogPause() {
        super.onDialogPause()
        mAgentWebBuilder?.onPause()
    }

    override fun onDismiss() {
        mAgentWebBuilder?.onDestroy()
        super.onDismiss()
    }

    /**
     * 初始化web加载到dialog
     */
    private fun initWebView() {
        if (fragment == null || mViewBinding == null) return

        mAgentWebBuilder = AgentWebBuilder(dialog = this)

        val webView = WebView(Utils.getApp())
        mAgentWebBuilder?.agentBuildCallBack = webCallBack
        mAgentWebBuilder?.onCreate(
            fragment = fragment!!,
            webContentView = mViewBinding!!.flContent,
            errorLayoutId = errorLayoutId,
            errorReLoadBtnId = errorReLoadBtnId,
            url = webUrl,
            webBGColor = webBGColor,
            webView = webView
        )
        mAgentWebBuilder?.mAgentWeb?.webCreator?.webParentLayout?.background = ColorDrawable(Color.TRANSPARENT)
    }

}